package src.other.beogold.u9c.utils;

import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 请求服务云接口加签
 * @Author: lys
 * @Date: 2025-09-10 14:38
 */
public class SignUtil {

    public static String tenant = "angeldev";

    public static String appid = "angel_neocrm";

    public static String secret = "HTsdNIHeHX2Cx14blMfIr7HwsK0AI3HbHAe8hOgR";

    private static final Logger logger = LoggerFactory.getLogger();

    public static void main(String[] args) {
        SignUtil signUtil = new SignUtil();
        String s = signUtil.signUrl("www.baidu.com");
        System.out.println("s = " + s);
    }

    public static String signUrl(String url) {

        //必要参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("$tenant", tenant);
        paramMap.put("$appid", appid);
        paramMap.put("$reqid", UUID.randomUUID());
        paramMap.put("$timestamp", System.currentTimeMillis());

        String signContent = getSignContentV0(paramMap, secret);
        String sign = sign(signContent, "UTF-8", secret);
        paramMap.put("$sign", sign);

        String params = paramMap.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.joining("&"));
        return url.indexOf("?") != -1 ? url + params : url + "?" + params ;
    }



    public static String getSignContentV0(Map<String,Object> params,String secretKey){
        if(params == null){
            return null;
        }
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);
        StringBuilder content = new StringBuilder();
        for (String key:keys) {
            Object value=params.get(key);
            if(value!=null)
                content.append(value);
        }
        content.append(secretKey);
        logger.info("【加签内容】【平台】" + content);
        return content.toString();
    }

    public static String sign(String content, String charset, String privateKey) {
        try {
            //判空content
            //判空私钥
            //判空编码类型
            charset = "UTF-8";
            return doSign(content, charset, privateKey);
        } catch (Exception e) {
            return "签名遭遇异常，请检查私钥格式是否正确。" + e.getMessage() +
                    " content=" + content + "，charset=" + charset + "，privateKeySize=" + privateKey.length();
        }
    }

    public static String doSign(String content, String charset, String secretKey) {
        String sign;
        try {
            sign = getSHA256StrJava(content).toUpperCase(Locale.ROOT);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        logger.info("【加签sign】【平台】】" + content);
        return sign;
    }

    /**
     * 利用java原生的摘要实现SHA256加密
     *
     * @param str 加密后的报文
     * @return
     */
    public static String getSHA256StrJava(String str) {
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes(StandardCharsets.UTF_8));
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            logger.info("getSHA256StrJava failed" + e);
        }
        return encodeStr;
    }

    /**
     * 将byte转为16进制
     *
     * @param bytes
     * @return
     */
    private static String byte2Hex(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder();
        String temp;
        for (byte aByte : bytes) {
            temp = Integer.toHexString(aByte & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                stringBuilder.append("0");
            }
            stringBuilder.append(temp);
        }
        return stringBuilder.toString();
    }
}
